<template>
    <Modal v-model:visible="isShowModal" title="修改密码" @ok="handleOk" @cancel="handleCancel" ok-text="提交"
        cancel-text="取消">
        <Form :model="formState" name="basic" ref="formRef" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }"
            autocomplete="off" :rules="rules">
            <FormItem label="账号" name="userName" :required="true">
                <Input v-model:value="formState.userName"></Input>
            </FormItem>
            <FormItem label="原密码" name="password" :required="true">
                <InputPassword v-model:value="formState.password"></InputPassword>
            </FormItem>
            <FormItem label="新密码" name="newPassword" :required="true">
                <InputPassword v-model:value="formState.newPassword"></InputPassword>
            </FormItem>
        </Form>
    </Modal>
</template>

<script lang="ts" setup>
import { Modal, Form, Input, message } from 'ant-design-vue'
import { useAuthStore } from '@/stores/auth';
import { Rule } from 'ant-design-vue/es/form';
import { AdminUserApi } from '@/api';

const FormItem = Form.Item;
const InputPassword = Input.Password;

const userinfo = useAuthStore().userInfo;
const isShowModal = ref(false)
const formState = ref({
    userName: '',
    password: '',
    newPassword: ''
})
const formRef = ref()
const rules: Record<string, Rule[]> = {
    userName: [{ required: true, message: "请输入账号", trigger: 'blur' }],
    password: [{ required: true, message: "请输入原密码", trigger: 'blur' }],
    newPassword: [{ required: true, message: "请输入旧密码", trigger: 'blur' }],
};
const handleOpen = () => {
    formState.value.userName = userinfo?.mobile || '';
    isShowModal.value = true;
}

const handleOk = () => {
    console.log('ok');
    formRef.value
        .validate()
        .then(async () => {
            let params = { password: formState.value.password, newPassword: formState.value.newPassword }
            await AdminUserApi.adminuserAdmineditpwd(params)
            message.success('修改成功')

            isShowModal.value = false; // 关闭弹窗
        })  
        .catch((err: any) => {
            console.log('校验失败', err);
        });
}

const handleCancel = () => {
    formState.value = {
        userName: '',
        password: '',
        newPassword: ''
    };
    isShowModal.value = false;
}

defineExpose({ handleOpen })
</script>